package com.ddy.test.creditcardmanage

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.ddy.test.creditcardmanage.common.Constant
import com.ddy.test.creditcardmanage.model.CardRecord
import com.ddy.test.creditcardmanage.model.CardViewModel
import kotlinx.android.synthetic.main.card_records.*
import java.text.SimpleDateFormat
import java.util.*

class CardRecordsActivity :  AppCompatActivity() {

    companion object {
        const val LOG_TAG = "CCM_RECORD"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.card_records)
        val cardName = this.intent.getStringExtra("cardName")
        title = "Records-$cardName"

        val cardId = this.intent.getLongExtra("cardId", 0)
        val records = CardViewModel(this.application).getAllCardRecords(cardId)
        records.observe(this, Observer {
            if(it.isEmpty()){
                cardRecordList.addView(LayoutInflater.from(this).inflate(R.layout.card_records_null, cardRecordList, false))
            }else{
                showRecords(it)
            }
        })

        fab.setOnClickListener {
            startActivity(Intent(this, AddCardRecord().javaClass)
                .putExtra("cardId", cardId)
                .putExtra("cardName", cardName)
            )
        }
    }


    private fun showRecords(records: List<CardRecord>) {
        val root = findViewById<LinearLayout>(R.id.cardRecordList)
        root.removeAllViewsInLayout()
        for(record in records){
            val item = LayoutInflater.from(this).inflate(R.layout.card_record_item, root, false)
//            val comment = item.findViewById<TextView>(R.id.cardRecordComment)
//            comment.text = ""
            val time = item.findViewById<TextView>(R.id.cardRecordTime)
            val dateTime = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA).format(Date(record.id))
            time.text = dateTime
            val amount = item.findViewById<TextView>(R.id.cardRecordAmount)
            if(record.recordType > 0) {
                amount.text = (("+" + record.amount))
            }else{
                amount.text = ("-" + record.amount)
            }
            root.addView(item)
            item.findViewWithTag<Button>(Constant.SWIPE_DELETE_ROW_BUTTON).setOnClickListener {
                CardViewModel(this.application).deleteCardRecord(record.id)
                root.removeView(item)
            }
        }
    }

}